<?php
class System_Model_CategoryMapper {
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('System_Model_DbTable_Category');
		}
		return $this->_dbTable;
	}
	public function save(System_Model_Category $category){
		try{
			$result=$this->getDbTable()->insert($category->toArray());
		}catch (Exception $e){
			return json_encode($category->toArray());
			return Utils_SQLErrorMsg::formatException($e);
		}
		return (int)$result;
	}
	public function update(System_Model_Category $category){
		if($category->getCat_id()){
			try{
				$result=$this->getDbTable()->update($category->toArray(), "cat_id=".$category->getCat_id());
			}catch(Exception $e){
				return Utils_SQLErrorMsg::formatException($e);
			}
		}else{
			return "没有找到该记录，无法更新";
		}
		return (int)$result;		
	}
	
	public function findAllCategory($id){
		$select=$this->getDbTable()->select()->from("category")->where("gauge_id=".$id);
		$data=array();
		try{
			$data=$this->getDbTable()->fetchAll($select)->toArray();
		}catch(Exception $e){
			return $e;
		}
		return $data;
	}
	
	public function findAll($gid,$curPage=1,$perPage=20){
		$rows=$this->getDbTable()->getAdapter()->fetchOne("select count(*) from category where gauge_id=".$gid);
		$select=$this->getDbTable()->select()->from("category")->where("gauge_id=".$gid)
						->limitPage($curPage,$perPage);
		$data=array();
		try{
			$data=$this->getDbTable()->fetchAll($select)->toArray();
		}catch(Exception $e){
			return $e;
		}
		$response=new stdClass();
		$response->page=$curPage;
		$response->total=ceil($rows/$perPage);
		$response->records=(int)$rows;
		$response->rows=$data;
		return $response;
	}
	
}
